package com.mobilepay.moneypig.timecount;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Created by xlm on 2017/8/14 0014
 */

public class CodeTimerService extends Service {
    public static final String IN_RUNNING = "code_running";
    public static final String END_RUNNING = "code_end";
    public String mobile;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mobile = intent.getStringExtra("mobile");
        // 第一个参数是总时间， 第二个参数是间隔
        CountDownTimer mCodeTimer = new CountDownTimer(90000, 1000) {
            @Override
            public void onStart() {

            }

            @Override
            public void onTick(long millisUntilFinished) {
                // 广播剩余时间
                broadcastUpdate(IN_RUNNING, millisUntilFinished / 1000 + "s", mobile);
            }

            @Override
            public void onFinish() {
                // 广播倒计时结束
                broadcastUpdate(END_RUNNING);
                // 停止服务
                stopSelf();
            }
        };
        // 开始倒计时
        mCodeTimer.start();
        return super.onStartCommand(intent, flags, startId);
    }

    // 发送广播
    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    // 发送带有数据的广播
    private void broadcastUpdate(final String action, String time, String mobile) {
        final Intent intent = new Intent(action);
        intent.putExtra("time", time);
        intent.putExtra("mobile", mobile);
        sendBroadcast(intent);
    }
}
